package cn.com.KnowNews.servlet;

import cn.com.KnowNews.entity.Admin;
import cn.com.KnowNews.entity.News;
import cn.com.KnowNews.service.IAdminService;
import cn.com.KnowNews.service.ICategoryService;
import cn.com.KnowNews.service.INewsService;
import cn.com.KnowNews.service.imlp.AdminServiceImpl;
import cn.com.KnowNews.service.imlp.CategoryServiceImpl;
import cn.com.KnowNews.service.imlp.NewsServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

@WebServlet(name = "LoginServlet",urlPatterns = "/login")
public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String path = request.getContextPath();
        String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";

        String code = request.getParameter("code");
        HttpSession session = request.getSession();
        String randStr = (String) session.getAttribute("randStr");
        PrintWriter out = response.getWriter();

        if (!code.equals(randStr)) {
            out.print("<script>alert('验证码错误！')</script>");
            response.setHeader("refresh","1;url="+basePath+"/admin/login.jsp");

        } else {

            IAdminService amdinService = new AdminServiceImpl();
            Admin admin = new Admin();
            admin.setUsername(request.getParameter("username"));
            admin.setPassword(request.getParameter("password"));
            Admin result;

            try {
                result = amdinService.login(admin);
                if (result != null) {
                    request.getSession().setAttribute("user", admin);
                    response.sendRedirect("ShowAllCategory");
                } else {
                    out.print("<script>alert('账号密码错误！')</script>");
                    response.setHeader("refresh","1;url="+basePath+"/admin/login.jsp");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }
}
